import time
import hmac
import base64
import hashlib
import requests
from urllib import parse
from typing import List


class DingTalk:
    """钉钉通知"""

    def __init__(self, **kwargs):
        self.webhook_url: str = ''
        self.app_secret: str = ''
        self.to_user: List[str] = []  # @某几个人
        self.to_all: bool = False  # 发送给所有人
        if kwargs:
            self.init(**kwargs)

    def init(self, webhook_url, app_secret, to_user, to_all):
        self.webhook_url = webhook_url
        self.app_secret = app_secret
        self.to_user = to_user
        self.to_all = to_all

    def _construct_url(self):
        """app_secret需要加签名
        """
        url = self.webhook_url

        if self.app_secret:  # 需要加密签名
            timestamp = '%d' % (time.time() * 1000)
            sign = f'{timestamp}\n{self.app_secret}'
            hash_ = hmac.new(self.app_secret.encode(), msg=sign.encode(), digestmod=hashlib.sha256)
            sign = parse.quote(base64.b64encode(hash_.digest()), safe='')
            url = f'{url}&sign={sign}&timestamp={timestamp}'
        return url

    def send(self, message):
        url = self._construct_url()

        body = {
            'msgtype': 'text',
            'text': {'content': message},
            'at': {'atMobiles': self.to_user,
                   'isAtAll': self.to_all,
                   }
        }

        resp = requests.post(url, json=body, headers={'Content-Type': 'application/json;charset=utf-8'}, verify=False)
        if resp.json().get('errcode') != 0:
            errmsg = resp.json().get('errmsg', '')
            raise Exception(errmsg)


dingtalk = DingTalk()


if __name__ == '__main__':
    dingtalk.init(webhook_url='https://oapi.dingtalk.com/robot/send?access_token=aba887f0db2e4dc8d0ac565ecfa1cd03',
                  app_secret='',
                  to_user=['15108404004'],
                  to_all=False)
    dingtalk.send('测试数据\naaa\naaabb')
